import qs from 'qs';
import service from './interceptor';
import { SUCCESS, ERROR } from './conf';

const $ajax = {
  get: (url, data = null) => {
    return new Promise((resolve, reject) => {
      service.get(url, {params: data}).then(response => {
        return resolve(response);
      }).catch(err => {
        return resolve({err});
      });
    })
  },
  post: (url, data = null) => {
    return new Promise((resolve, reject) => {
      service.post(url, data).then(response => {
        return resolve(response);
      }).catch(err => {
        return resolve({err});
      });
    })
  }
}

export default {
  async get (url, params = {}) {
    const res = await $ajax.get(url, params);
    if (Number(res.code) === SUCCESS) {
      return res && res.data;
    } else if (res.err) {
      console.log({ code: ERROR, err: res.err });
    }
  },
  async post (url, params = {}) {
    const res = await $ajax.post(url, qs.stringify(params));
    if (Number(res.code) === SUCCESS) {
      return res && res.data;
    } else if (res.err) {
      console.log({ code: ERROR, err: res.err });
    }
  }
};
